package ucap.com.lesanapp.activitys;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Environment;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AbsListView;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.umeng.analytics.MobclickAgent;

import java.io.File;

import butterknife.Bind;
import butterknife.ButterKnife;
import ucap.com.lesanapp.R;
import ucap.com.lesanapp.view.HelpViewDialog;
import ucap.com.lesanapp.view.LodingDialog;
import ucap.com.lesanapp.view.UpDateDialog;

public class SettingsActivity extends AppCompatActivity implements View.OnClickListener {
    @Bind(R.id.iv_back)
    ImageView ivBack;
    @Bind(R.id.rl_settings_model)
    RelativeLayout rlSettingsModel;
    @Bind(R.id.rl_item_clear_cache)
    RelativeLayout rlClearCache;
    @Bind(R.id.rl_about)
    RelativeLayout rlAbout;
    @Bind(R.id.rl_update)
    RelativeLayout rlUpdate;
    @Bind(R.id.tv_cache)
    TextView tvCache;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_settings);
        ButterKnife.bind(this);
        intiView();

    }

    private void intiView() {
        rlSettingsModel.setOnClickListener(this);
        rlClearCache.setOnClickListener(this);
        rlAbout.setOnClickListener(this);
        ivBack.setOnClickListener(this);
        rlUpdate.setOnClickListener(this);
        try {
            String cache = getTotalCacheSize(this);
            tvCache.setText(cache);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取缓存大小
     *
     * @param context
     * @return
     * @throws Exception
     */
    public static String getTotalCacheSize(Context context) throws Exception {
        long cacheSize = getFolderSize(context.getCacheDir());
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            cacheSize += getFolderSize(context.getExternalCacheDir());
        }
        return getFormatSize(cacheSize);
    }

    /**
     * 计算缓存
     *
     * @param cacheSize
     * @return
     */
    private static String getFormatSize(long cacheSize) {

        return (double) ((cacheSize / 1024) / 1024) + "MB";
    }

    /**
     * 根据目录查找缓存
     *
     * @param file
     * @return
     * @throws Exception
     */
    public static long getFolderSize(File file) throws Exception {
        long size = 0;
        try {
            File[] fileList = file.listFiles();
            for (int i = 0; i < fileList.length; i++) {
                // 如果下面还有文件
                if (fileList[i].isDirectory()) {
                    size = size + getFolderSize(fileList[i]);
                } else {
                    size = size + fileList[i].length();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return size;
    }

    /**
     * 清除指定缓存
     *
     * @param dir
     * @return
     */
    private static boolean deleteDir(File dir) {
        if (dir != null && dir.isDirectory()) {
            String[] children = dir.list();
            for (int i = 0; i < children.length; i++) {
                boolean success = deleteDir(new File(dir, children[i]));
                if (!success) {
                    return false;
                }
            }
        }
        return dir.delete();
    }

    /**
     * 清除缓存
     *
     * @param context
     */
    public static void clearAllCache(Context context) {
        deleteDir(context.getCacheDir());
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            deleteDir(context.getExternalCacheDir());
        }
    }


    @Override
    public void onClick(View v) {
        if (v == ivBack) {
            finish();
        } else if (v == rlSettingsModel) {
            Intent intent = new Intent();
            intent.setClass(SettingsActivity.this, SettingsModelActivity.class);
            startActivity(intent);
        } else if (v == rlClearCache) {
            AlertDialog.Builder dialog = new AlertDialog.Builder(this);
            dialog.setMessage("确定清除缓存!");
            dialog.setTitle("提示");
            dialog.setNegativeButton("取消", null);
            dialog.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    try {
                        clearAllCache(getApplicationContext());
                        tvCache.setText("0.0MB");
                        Toast.makeText(getApplicationContext(), "清理成功!", Toast.LENGTH_SHORT).show();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
            try {
                long temp = getCacheSize();
                if (temp > 0) {
                    dialog.show();
                } else {
                    Toast.makeText(getApplicationContext(), "当前没有缓存清理!", Toast.LENGTH_SHORT).show();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else if (v == rlAbout) {
            HelpViewDialog.showDialog(this);
        } else if (v == rlUpdate) {
            LodingDialog.showDialog(this);
        }
    }

    /**
     * 获取清理后的缓存
     *
     * @return
     * @throws Exception
     */
    private long getCacheSize() throws Exception {
        long temp = getFolderSize(getApplicationContext().getCacheDir());
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            temp += getFolderSize(getApplicationContext().getExternalCacheDir());
        }
        return temp;
    }

    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);//友盟统计
    }

    public void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }
}
